
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCHello {
    public static void main(String[] args) throws SQLException {
        // 1.使用 DataSource 描述 Mysql 服务器的位置
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java104?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1234");

        // 2.和数据库服务器建立连接
        Connection connection = dataSource.getConnection();
        //System.out.println(connection);

        // 3.构造 SQL 语句,JDBC 操作数据库，本质仍然是通过 SQL 来描述数据库操作
        // 例如插入一条数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号：");
        int num = scanner.nextInt();
        System.out.println("请输入姓名：");
        String name = scanner.next();

        // String sql = "insert into student values(" + num + ",'" + name + "')";
        String sql = "insert into student values(?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, num);
        statement.setString(2, name);

        // 4.
        int n = statement.executeUpdate();
        System.out.println("n = " + n);

        // 5.断开连接,释放资源
        statement.close();
        connection.close();
    }
}
